//
//  FirstViewController.swift
//  CPT3
//
//  Created by onemade on 12/7/15.
//  Copyright © 2015 CNPC. All rights reserved.
//

import UIKit

let fileName = "cnpc.png"
class FirstViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    @IBOutlet weak var imageView: UIImageView!
    var imagePicker: UIImagePickerController!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.createEidtableCopyOfDatabaseIfNeeded()
        imageView.image = UIImage(named: fileName)
    }

    func createEidtableCopyOfDatabaseIfNeeded(){
        let fileManager = NSFileManager.defaultManager()
        let writableDBPath = applicationDocumentsDirectoryFile()
        let dbExist = fileManager.fileExistsAtPath(writableDBPath)
        
        if !dbExist {
            let defaultDBPath = NSBundle.mainBundle().resourcePath?.stringByAppendingString("/"+fileName)
            do {
                try fileManager.copyItemAtPath(defaultDBPath!, toPath: writableDBPath)
            }catch let e as NSError{
                print(e.debugDescription)
            }
            
        }
    }
    
    func applicationDocumentsDirectoryFile() -> String {
        let documentsDirectorys = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let documentDirectory = documentsDirectorys[0]
        let path = documentDirectory.stringByAppendingString("/"+fileName)
        return path
    }

    @IBAction func loadImage(sender: UIButton) {
        let identifier = sender.restorationIdentifier
        
        switch identifier! {
            case "loadBundle":
                let imagePath = NSBundle.mainBundle().pathForResource("icon", ofType: "png")
                let img = UIImage(contentsOfFile: imagePath!)
                imageView.image = img!
            case "loadSandbox":
                let imagePath = applicationDocumentsDirectoryFile()
                imageView.image = UIImage(contentsOfFile: imagePath)
            case "loadWebService":
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
                    let strURL = String(format: "http://cdn2.raywenderlich.com/wp-content/uploads/2014/12/1-AddButtonFinal.png", arguments:[])
                    let url = NSURL(string: strURL)
                    let data = NSData(contentsOfURL: url!)
                    self.imageView.image = UIImage(data: data!)
                })

            case "pickPhotoLibrary":
                if imagePicker == nil {
                    imagePicker = UIImagePickerController()
                }
                imagePicker.delegate = self
                imagePicker.sourceType = .SavedPhotosAlbum
                presentViewController(imagePicker, animated: true, completion: {})
            case "pickPhotoCamera":
//                UIImagePickerController.isCameraDeviceAvailable(.Front/.Rear) 判断是否支持ios设备前后摄像头
                if UIImagePickerController.isSourceTypeAvailable(.Camera){
                    if imagePicker == nil {
                        imagePicker = UIImagePickerController()
                    }
                    imagePicker.delegate = self
                    imagePicker.sourceType = .Camera
                    presentViewController(imagePicker, animated: true, completion: {})
                }
            default: break
        }
    }
}

private typealias imagePickerControllerDelegationController = FirstViewController
extension imagePickerControllerDelegationController{
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        imagePicker.delegate = nil
        dismissViewControllerAnimated(true, completion: {})
    }
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let originalImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        imageView.image = originalImage
        imageView.contentMode = .ScaleToFill
        imagePicker.delegate = nil
        dismissViewControllerAnimated(true, completion: {})
    }
}
